<template>
  <AppTitle title="商品添加"></AppTitle>
  <div class="form-box">
    <!-- 使用 ref 绑定到表单 -->
    <el-form hide-required-asterisk="false" ref="formRef" style="max-width: 600px" :model="goodsForm" :rules="rules"
      label-width="auto">
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="goodsForm.name" />
      </el-form-item>
      <el-form-item label="商品分类" @click="getCategoryName()">
        <el-select v-model="goodsForm.category" placeholder="请选择商品分类">
        <el-option v-if="categoriesName" v-for="(item,index) in categoriesName" :key="index" :label="item.cateName" :value="item.cateName" />
      </el-select>
      </el-form-item>
      <el-form-item label="商品价格" prop="price">
        <el-input-number v-model="goodsForm.price" :step="1" />
      </el-form-item>
      <el-form-item label="商品图片" prop="imgUrl">
        <el-upload
          class="avatar-uploader"
          :action="'/api' + '/goods/goods_img_upload'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="goodsForm.imgUrl" :src="serverUrl + goodsForm.imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="商品描述" prop="goodsDesc">
        <el-input v-model="goodsForm.goodsDesc" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">
          添加
        </el-button>
        <el-button @click="resetForm(goodsForm)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import AppTitle from '@/components/AppTitle.vue';
import { goodsAdd, goodsCategories} from '@/api/goods';
import { reactive, ref } from 'vue';
import { serverUrl } from '@/utils/common';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
const router = useRouter();
// 使用 ref 定义表单引用
const formRef = ref(null);
const categoriesName = ref();
// 定义表单数据对象
const goodsForm = reactive({
  name: '',
  category: '',
  price: 0,
  imgUrl: '',
  goodsDesc: ''
});
// 获取分类名称
const getCategoryName = async () => {
  let res = await goodsCategories();
  console.log(res);
  categoriesName.value = res.categories;
 
}

// 定义表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  goodsDesc: [
    { required: true, message: '请输入商品描述', trigger: 'blur' }
  ]
});



const submitForm = async () => {
  // 可以在这里使用 formRef 调用表单方法，如验证等
  goodsForm.imgUrl = goodsForm.imgUrl.slice(23);
  let res = await goodsAdd(goodsForm);
  console.log(res);
if(res.code == 0) {
  ElMessage.success('商品添加成功');
  // 添加成功后，跳转页面
  router.push('/GoodsList');
}else {
  ElMessage.error('商品添加失败');
}

  
};

const resetForm = () => {
  goodsForm.name = '';
  goodsForm.price = 0;
  goodsForm.category = '';
  goodsForm.imgUrl = '';
  goodsForm.goodsDesc = '';
};

const handleAvatarSuccess = (response) => {
    // 假设服务器返回的响应中有一个字段是图片的 URL
    if (response && response.imgUrl) {
      goodsForm.imgUrl = response.imgUrl;
    }
    ElMessage.success('图片上传成功');
};

const beforeAvatarUpload = (file) => {
    console.log(file);
    if(!file.type.includes('image')){
      ElMessage.error('文件类型不是图片');
      return false;
    }
    if(file.size >2*1024*1024){
      ElMessage.error('文件大小不能超过 2M');
      return false;
    }
  return true ;  
}
</script>

<style lang="scss" scoped>
.form-box {
  width: 100%;
  height: auto;
  overflow: hidden;
}

:deep(.el-form) {
  width: 100%;
  height: auto;
  padding: 15px;

  .el-form-item img {
    width: 178px;
    height: 178px;
    border: 1px dashed #ccc;
    background-image: url('@/assets/img/addImg.png');
    background-size: 178px 178px;
  }

  .avatar-uploader {
    width: 178px;
    height: 178px;
    border: 1px dashed #ccc;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
  }
}
</style>